//
//  SXTopicListViewController.m
//  ShiXun
//
//  Created by lanou on 15/10/27.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXTopicListViewController.h"
#import "SXTopicListTableViewCell.h"
#import "SXRequestManager.h"
#import "SXDataBaseManager.h"
#import "SXTopicListModel.h"
#import "UIImageView+WebCache.h"
#import "SXTopicListForumModel.h"
#import "SXTopicDetailsViewController.h"
#import "UMSocial.h"
#import "SXCollectionManager.h"

@interface SXTopicListViewController () <UITableViewDelegate,UITableViewDataSource,UMSocialUIDelegate>
@property (nonatomic, strong) SXTopicListForumModel *forumModel;
@property (nonatomic, strong) UIAlertController *alertTs;
@property (nonatomic, strong) UIView *headerView;

@end

@implementation SXTopicListViewController

- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:(UITableViewStylePlain)];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.showsVerticalScrollIndicator = NO;
        [_mainTableView registerClass:[SXTopicListTableViewCell class] forCellReuseIdentifier:@"listTableViewCell"];
    }
    return _mainTableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _start = 0;
    _limit = 20;
    _isRefreshMore = NO;
    
    self.navigationController.navigationBar.hidden = NO;
    
    [self requestData];
}

// 网络请求
- (void)requestData
{
    NSString *urlString = [kTopicListURLString stringByAppendingString:_forum_id];
//    NSLog(@"%@",urlString);
    
    [SXRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        [self removeLoadingView];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
        NSArray *modelArray = dic[@"finfo_list"];
        self.dataSourceArray = nil;
        for (NSDictionary *modelDic in modelArray) {
            SXTopicListModel *listModel = [[SXTopicListModel alloc] init];
            [listModel setValuesForKeysWithDictionary:modelDic[@"thread"]];
            [self.dataSourceArray addObject:listModel];
        }

        NSDictionary *forumDic = dic[@"forum_info"];
        _forumModel = [[SXTopicListForumModel alloc] init];
        [_forumModel setValuesForKeysWithDictionary:forumDic];
        
        self.navigationItem.title = _forumModel.forum_name;
        _mainTableView.tableHeaderView = self.headerView;
        
        [_mainTableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"数据请求失败：%@",error);
        [self removeLoadingView];
    }];

}

// 分享
- (void)ChangeShare:(UIButton *)button
{
    // 分享后是否提示（YES是不提示）
    [UMSocialConfig setFinishToastIsHidden:NO position:(UMSocialiToastPositionCenter)];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5632c41ce0f55a17390010c1"
                                      shareText:[NSString stringWithFormat:@"更多精彩内容等你来看，点击进入详情：%@",self.forumModel.share_url]
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                       delegate:self];
}
- (void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"分享成功：%@",[[response.data allKeys] objectAtIndex:0]);
    }
}
//点击 cell 进入详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXTopicDetailsViewController *detailsVC = [[SXTopicDetailsViewController alloc] init];
    detailsVC.thread_id = [_dataSourceArray[indexPath.row] thread_id];
    [self.navigationController pushViewController:detailsVC animated:YES];
}
// 表头设置
- (UIView *)headerView
{
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    UIImageView *imageT = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    imageT.image = [UIImage imageNamed:@"T1"];
    [_headerView addSubview:imageT];
    
    UIImageView *avatar_urlImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 60, 60)];
    [avatar_urlImage sd_setImageWithURL:[NSURL URLWithString:_forumModel.avatar_url]];
    [_headerView addSubview:avatar_urlImage];
    
    UILabel *forum_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, kScreenWidth * 2/3, 30)];
    forum_nameLabel.text = _forumModel.forum_name;
    [_headerView addSubview:forum_nameLabel];
    
    UILabel *onlookers_countLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 45, kScreenWidth / 4, 25)];
    onlookers_countLabel.text = [NSString stringWithFormat:@"%@人关注",_forumModel.onlookers_count];
    onlookers_countLabel.font = [UIFont systemFontOfSize:14];
    [_headerView addSubview:onlookers_countLabel];
    
    UILabel *talk_countLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth / 5 + 120, 45, kScreenWidth / 5, 25)];
    talk_countLabel.text = [NSString stringWithFormat:@"%@帖子",_forumModel.talk_count];
    talk_countLabel.font = [UIFont systemFontOfSize:14];
    [_headerView addSubview:talk_countLabel];
    
    
    return _headerView;
}
// cell 设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXTopicListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listTableViewCell" forIndexPath:indexPath];
    
    cell.configureModel = _dataSourceArray[indexPath.row];
    [cell.shareButton addTarget:self action:@selector(ChangeShare:) forControlEvents:(UIControlEventTouchUpInside)];
        
    cell.collectionButton.tag = indexPath.row + 300;
    cell.collectionButton.selected = [SXCollectionManager checkCollectionWithTableName:@"topic" urlID:[_dataSourceArray[indexPath.row]  thread_id]];
      [cell.collectionButton addTarget:self action:@selector(ChangeCollection:) forControlEvents:UIControlEventTouchUpInside];
    
        cell.collectionB.tag = indexPath.row + 300;
    [cell.collectionB addTarget:self action:@selector(ChangeCollection:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.collectionB.selected = cell.collectionButton.selected;
    cell.collectionButton.selected = cell.collectionB.selected;
    return cell;
}
// 点击收藏
- (void)ChangeCollection:(UIButton *)button
{
    NSInteger a = button.tag - 300;
    button.selected = !button.selected;
    NSString *message = nil;
    if (button.selected) {
        message = @"收藏成功";
    }else {
        message = @"取消收藏成功";
    }
    [SXCollectionManager  collectionDataWithTableName:@"topic" title:[_dataSourceArray[a] content] urlID:[_dataSourceArray[a] thread_id] isCollection:button.selected finish:^(BOOL isSuccessed) {
        if (isSuccessed) {
            _alertTs = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
            [self presentViewController:_alertTs animated:YES completion:nil];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doTapCollection:) userInfo:nil repeats:NO];
        }else {
            NSLog(@"收藏失败！");
        }
    }];
    [_mainTableView reloadData];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mainTableView reloadData];
}

- (void)doTapCollection:(NSTimer *)timer
{
    [_alertTs dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// cell 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger a = [[_dataSourceArray[indexPath.row] thumbImageArray] count];
    if (a == 0) {
        CGFloat height = [SXTopicListTableViewCell heightOfContent:[_dataSourceArray[indexPath.row] content]] + 100;
        return height;
    }else if (a == 1) {
    CGFloat height = [SXTopicListTableViewCell heightOfContent:[_dataSourceArray[indexPath.row] content]] + 100 + (kScreenWidth - 30) / 3 + 30 ;
        return height;
    }
    else if (a < 4 ) {
        CGFloat height = [SXTopicListTableViewCell heightOfContent:[_dataSourceArray[indexPath.row] content]] + 100 + (kScreenWidth - 30) / 3 ;
        return height;
    }else if (a > 3 && a < 7) {
        CGFloat height = [SXTopicListTableViewCell heightOfContent:[_dataSourceArray[indexPath.row] content]] + 110 + 2 *((kScreenWidth - 30) / 3);
        return height;
    }else {
       CGFloat height = [SXTopicListTableViewCell heightOfContent:[_dataSourceArray[indexPath.row] content]] + 120 + 3 * ((kScreenWidth - 30) / 3);
        return height;
    }

}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
